<script setup>
import { ref, reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { inspectionMap } from "@/api/inspection/resource-manage.js";
import { getToken } from "@/utils/auth.js";

// 接收props
const props = defineProps({
  visible: { type: Boolean, default: false },
});
const { visible } = toRefs(props);
const emit = defineEmits(["update:visible", "handleQuery"]);

// 关闭弹窗
function onCloseDialog() {
  emit("update:visible", false);
  emit("handleQuery");
  ruleFormRef.value.resetFields();
}

// 表单数据
const formData = ref({
  name: null,
  url: null,
});

// 上传相关方法
const loading = ref(false);
const upload = {
  onSuccess(response) {
    formData.value.url = response.message;
    loading.value = false;
  },
  beforeUpload() {
    loading.value = true;
  },
};

// 表单校验规则
const ruleFormRef = ref();
const rules = reactive({
  name: { required: true, message: "该选项不能为空", trigger: "blur" },
  url: { required: true, message: "该选项不能为空", trigger: "blur" },
});

async function onSubmit(formEl) {
  if (!formEl) return;
  // 表单校验
  await formEl.validate(async (valid) => {
    if (valid) {
      await ElMessageBox.confirm("确认继续操作吗", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      });
      const { message } = await inspectionMap.create(formData.value);
      ElMessage({ type: "success", message });
      onCloseDialog();
    } else {
      // console.log(fields);
    }
  });
}
</script>

<template>
  <el-dialog
    :model-value="visible"
    title="上传地图"
    width="800px"
    top="32vh"
    :close-on-click-modal="false"
    :show-close="false"
    @close="onCloseDialog()"
  >
    <el-form
      ref="ruleFormRef"
      v-loading="loading"
      :rules="rules"
      :model="formData"
      label-width="100px"
      label-suffix="："
    >
      <el-form-item label="地图名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="地图链接" prop="url">
        <el-input v-model="formData.url" class="w-[556px] mr-4" disabled />
        <el-upload
          :headers="{ Authorization: getToken() }"
          :show-file-list="false"
          :on-success="upload.onSuccess"
          :before-upload="upload.beforeUpload"
          :limit="1"
          action="http://test.zhenxiangsimple.cn/api/file/upload"
          accept="image/*"
        >
          <el-button type="primary" plain>选择文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(ruleFormRef)">
          确认
        </el-button>
        <el-button @click="onCloseDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
